#include <stdio.h>
#include "des_list.h"

DESELEM* DESELEM_malloc(uint8_t *des_buf) {
	DESELEM *elem;
	int len;

	if(!des_buf) return NULL;

	elem = (DESELEM*)os_calloc(sizeof(DESELEM));
	if(!elem) return NULL;

	len = 2 + des_buf[1];
	memcpy(elem->buf, des_buf, len);

	return elem;
}

void DESELEM_free(DESELEM *elem) {
	if(!elem) return;
	os_free(elem);
}


LIST_XXXX(DESELEM, node);


// 描述符链表在表中的生成,生成段的时候调用
int DESELEM_LIST_get_buf(LIST *des_list, uint8_t *buf, int buf_size, int *err_flag) {
	int pos = 0;
	int des_len;
	DESELEM *des_elem;

	if(!des_list || !buf || !buf_size || !err_flag) return 0;

	*err_flag = 0;
	list_for_each_entry(des_elem, &des_list->node, node, DESELEM) {
		des_len = 2 + des_elem->buf[1];
		if(pos + des_len > buf_size) {
			*err_flag = 1;
			return 0;
		}
		memcpy(buf + pos, des_elem->buf, des_len);
		pos += des_len;
	}

	return pos; // 数据占用空间大小
}


int DESELEM_buf_set_service(uint8_t des_buf[DES_BUF_MAX_LEN], PRGELEM *prg_elem) {
	int pos = 0;
	int pro_name_len, prg_name_len;

	if(!des_buf || !prg_elem) return 0;

	pro_name_len = (int)strlen(prg_elem->pro_name);
	prg_name_len = (int)strlen(prg_elem->prg_name);

	// 1B-des_tag
	des_buf[pos++] = 0x48;

	// 1B-des_len-后面补写
	des_buf[pos++] = 0;

	// 1B-service_type(prg_type)
	des_buf[pos++] = prg_elem->prg_type;

	// prg长度调节
	if((pos + (1 + 0) + (1 + prg_name_len)) > DES_BUF_MAX_LEN)
		prg_name_len = DES_BUF_MAX_LEN - (pos + 1 + 1);
	// pro长度调节
	if((pos + (1 + pro_name_len) + (1 + prg_name_len)) > DES_BUF_MAX_LEN)
		pro_name_len = DES_BUF_MAX_LEN - (pos + 1 + 1 + prg_name_len);

	// pro
	des_buf[pos++] = pro_name_len;
	memcpy(des_buf + pos, prg_elem->pro_name, pro_name_len);
	pos += pro_name_len;

	// prg
	des_buf[pos++] = prg_name_len;
	memcpy(des_buf + pos, prg_elem->prg_name, prg_name_len);
	pos += prg_name_len;

	// 补写描述符长度
	des_buf[1] = pos - 2;

	return pos;
}
